<?php


namespace app\index\controller;


use app\common\controller\Basecontroller;
use app\common\controller\Send;
use app\validate\Vali;
use app\index\model\User;
use think\Db;
use think\facade\Cache;
use think\Request;

class Login extends Basecontroller
{

    /**
     * 发送短信验证码接口
     * ywh开发
     * 接口是否开发完：否
     * @param Vali $Validate
     * @param Request $request
     * @return string|\think\response\Json|void
     */
    public function messageCode(Vali $Validate,Request $request){
        $config = [
            'phone'     =>      $request->post('phone'),
            'Code'      =>      rand(1000,9999)
        ];
        if (!$Validate->scene('verifiCode')->check($config)) return $this->returnJson(self::ERROR,'手机号格式错误',$Validate->getError());
        Send::send($config['phone'],$config['Code']);
        Cache::set($config['phone'],$config['Code'],60);
        return $this->returnJson(self::OK,'验证码发送成功');
    }

    /**
     * 初始化用户信息
     * ywh
     *
     * @param $userID
     */
    public function registerMess($userID){
        $user_id = json_decode($userID)->user_id;
        Db::startTrans();
        try {
            Db::table('project')->insert(['user_id' => $user_id]);
            Db::table('study')->insert(['user_id' => $user_id]);
            Db::table('userstatus')->insert(['user_id' => $user_id]);
            Db::table('experience')->insert(['user_id' => $user_id]);
            Db::table('certificate')->insert(['user_id' => $user_id]);
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
        }
    }

    /**
     *手机号注册接口
     * ywh开发
     * 接口是否开发完：否
     * @param Request $request
     * @param User $userModel
     * @return \think\response\Json
     */
    public function phoneRegister(Request $request , User $userModel){
        $data = [
            'phone' => $request->post('phone'),
            'code'   => $request->post('code')
        ];
        $redisResult = Cache::get($data['phone']);
        if (!$this->isExistence($data['phone'])) return $this->returnJson(self::ERROR,'此账户已存在');
        if (!$redisResult) return $this->returnJson(self::ERROR,'手机号不正确');
        if ($data['code'] != $redisResult) return $this->returnJson(self::ERROR,'验证码错误');
        $save = [
            'phone'             =>       $data['phone'],
            'username'       =>       '新用户_' . rand(1000,9999),
            'create_time'    =>        time(),
            'update_time'   =>        time()
        ];
        if (!$userModel->push($save)) return $this->returnJson(self::ERROR,'服务器出错');
        $userID = $userModel->selectUserID($data['phone']);
        $this->registerMess($userID);
        return $this->returnJson(self::JUMP,'注册成功');
    }

    /**
     * 密码注册接口
     * ywh开发
     * 接口是否开发完：否
     * @param Vali $Validate
     * @param User $userModel
     * @param Request $request
     * @return string|\think\response\Json|void
     */
    public function passRegister(Vali $Validate , User $userModel , Request $request){
        $checkMess = [
            'phone'             =>      $request->post('phone'),
            'password'        =>      $request->post('password'),
            'rePassword'    =>       $request->post('rePassword')
        ];
        if (!$Validate->scene('passRegister')->batch()->check($checkMess)) return $this->returnJson(self::ERROR,'数据格式错误',$Validate->getError());
        if (!$this->isExistence($checkMess['phone'])) return $this->returnJson(self::ERROR,'此账户已存在');
        $salt = md5(rand(1000,9999));
        $data = [
            'phone'             =>       $checkMess['phone'],
            'salt'                 =>       $salt,
            'password'       =>        md5($salt . md5($checkMess['password'])),
            'username'       =>       '新用户_' . rand(1000,9999),
            'create_time'    =>        time(),
            'update_time'   =>        time()
        ];
        if (!$userModel->push($data)) return $this->returnJson(self::ERROR,'数据库错误');
        $userID = $userModel->selectUserID($data['phone']);
        $this->registerMess($userID);
        return $this->returnJson(self::JUMP,'注册成功');
    }

    /**
     * 手机号登录接口
     * ywh开发
     * 接口是否开发完：否
     * @param Request $request
     * @param User $userModel
     * @return \think\response\Json
     */
    public function phoneLogin(Request $request , User $userModel){
        $data = [
            'phone' => $request->post('phone'),
            'code'   => $request->post('code')
        ];
        $redisResult = Cache::get($data['phone']);
        if ($data['code'] != $redisResult) return $this->returnJson(self::ERROR,'验证码错误');
        if ($this->isExistence($data['phone'])) {
            $save = [
                'phone'             =>       $data['phone'],
                'username'       =>       '新用户_' . rand(1000,9999),
                'create_time'    =>        time(),
                'update_time'   =>        time()
            ];
            if (!$userModel->save($save)) return $this->returnJson(self::ERROR,'数据库报错');
            $userID = $userModel->selectUserID($data['phone']);
            $this->registerMess($userID);
            $message = '注册并登录成功';
        }
        if (empty($message))  $message = '登录成功';
        $result = $userModel->getOneAttr('phone','=',$data['phone']);
        $token = [
            'phone'         =>      $data['phone'],
            'user_id'       =>      $result['user_id'],
            'position'      =>       $result['position']
        ];
        return $this->returnJson(self::JUMP,$message,['token' => $this->createToken($token) , 'position' => $token['position']]);
    }

    /**
     * 密码登录接口
     * ywh开发
     * 接口是否开发完：否
     * @param User $userModel
     * @param Vali $Validate
     * @param Request $request
     * @return \think\response\Json
     */
    public function passLogin(User $userModel , Request $request , Vali $Validate){
        $data = [
            'phone'            =>       $request->post('phone'),
            'password'      =>        $request->post('password')
        ];
        if ($this->isExistence($data['phone'])) return $this->returnJson(self::ERROR,'账户输入错误或未注册');
        if (!$Validate->scene('passLogin')->batch()->check($data)) return $this->returnJson(self::ERROR,'数据格式错误',$Validate->getError());
        $mdPass = md5($data['password']);
        $result = $userModel->getOneAttr('phone','=',$data['phone']);
        if ($result['password'] != md5($result['salt'] . $mdPass)) return $this->returnJson(self::ERROR,'密码错误');
        $token = [
            'phone'         =>      $data['phone'],
            'user_id'       =>      $result['user_id'],
            'position'      =>       $result['position']
        ];
        return $this->returnJson(self::JUMP,'登录成功',['token' => $this->createToken($token) , 'position' => $token['position']]);
    }

    /**找回密码中的验证身份接口
     * ywh开发
     * 接口是否完成：否
     * @param Request $request
     * @param User $userModel
     * @param Vali $Validate
     * @return \think\response\Json
     */
    public function verifyPhoneCode(Request $request , User $userModel , Vali $Validate){
        $data = [
            'phone' => $request->post('phone'),
            'pullCode'=> $request->post('Code')
        ];
        $code = Cache::get($data['phone']);
        if (!$code) return $this->returnJson(self::ERROR,'手机号错误');
        if (!$userModel->getOneAttr('phone','=',$data['phone'])) return $this->returnJson(self::ERROR,'手机号暂未注册');
        if (!$data['pullCode'] == $code) return $this->returnJson(self::ERROR,'验证码错误');
        return $this->returnJson(self::JUMP,'验证码正确');
    }

    /**
     * 找回密码中的重置密码接口
     * ywh开发
     * 接口是否开发完：否
     * @param Request $request
     * @param User $userModel
     * @param Vali $Validate
     * @return \think\response\Json
     */
    public function passRetrieve(Request $request , User $userModel , Vali $Validate){
        $data = [
                'phone'             =>    $request->post('phone'),
                'password'        =>    $request->post('password'),
                'rePassword'        =>    $request->post('rePassword')
        ];
        if (!$Validate->scene('passRegister')->batch()->check($data)) return $this->returnJson(self::ERROR ,'手机号和密码格式不正确',$Validate->getError());
        if ($data['password'] != $data['rePassword']) return $this->returnJson(self::ERROR,'密码和确认密码不一致');
        $result = $userModel->getOneAttr('phone','=' , $data['phone']);
        $retrievePass = md5(md5($data['password']) . $result['salt']);
        if (!$userModel->save(['password'   =>  $retrievePass],['phone'  =>  $data['phone']])) return $this->returnJson(self::ERROR,'数据库错误');
        return $this->returnJson(self::JUMP,'修改密码成功');
    }

    /**创建token函数，用于登录接口返回数据时调用
     * ywh开发
     * 是否开发完：否
     * @param $data
     * @return string
     */
    public function createToken($data){
        $token = md5(md5($data['phone']) . md5($data['user_id']) . rand(10000,99999));
        Cache::set($token,json_encode($data),60*60*24);
        return $token;
    }
}